<template>
  <div style="background-color: #fff;">
    <!-- 渲染顶层工序 -->
    
      <div v-for="(itemdata, indexdata) in hierarchy" style="min-width:200px;margin:10% auto;">
        
              <vue2-org-tree
                :data="itemdata"
                :horizontal="horizontal"
                :label-class-name="labelClassName"
                collapsable
                :zoom="zoom"
                :pan="pan"
                :render-content="renderContent"
                @on-expand="onExpand"
                @on-node-click="NodeClick"
                v-slot:toggle-icon="{ node, expanded }">

              </vue2-org-tree>
      </div>
    
  </div>
</template>

<script>
export default {
  data() {
    return {
      labelClassName: "bg-color-orange",
        BasicSwich: false,
        BasicInfo: {},
        checked: true,
        horizontal: true,
        checked2: true,
        zoom: true,
		   pan: true,
      hierarchy: [], // 存储转换后的工序层级结构
      rowData: [
    {
        "id": 145253,
        "peijianxuhao": 1,
        "daogongxu": "外发深镭射",
        "shengchanzhouqi": 13,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "白架",
        "bengongxuid": "烧焊",
        "bengongxu": "烧焊",
        "daogongxuid": "外发深镭射",
        "daopeijianleixing": ""
    },
    {
        "id": 146193,
        "peijianxuhao": 2,
        "daogongxu": "金打磨",
        "shengchanzhouqi": 2,
        "gongyinandu": null,
        "laiyuan": "外发",
        "peijianleixing": "白架",
        "bengongxuid": "外发深镭射",
        "bengongxu": "外发深镭射",
        "daogongxuid": "金打磨",
        "daopeijianleixing": ""
  
    },
    {
        "id": 11519,
        "peijianxuhao": 3,
        "daogongxu": "外发电镀",
        "shengchanzhouqi": 6,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "白架",
        "bengongxuid": "金打磨",
        "bengongxu": "金打磨",
        "daogongxuid": "外发电镀",
        "daopeijianleixing": "金属色架"
    },
    {
        "id": 131028,
        "peijianxuhao": 1,
        "daogongxu": "包装装配",
        "shengchanzhouqi": 4,
        "gongyinandu": null,
        "laiyuan": "外发",
        "peijianleixing": "金属色架",
        "bengongxuid": "外发电镀",
        "bengongxu": "外发电镀",
        "daogongxuid": "包装装配",
        "daopeijianleixing": ""
  
    },
    {
        "id": 122214,
        "peijianxuhao": 2,
        "daogongxu": "成品仓",
        "shengchanzhouqi": 7,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "金属色架",
        "bengongxuid": "包装装配",
        "bengongxu": "包装装配",
        "daogongxuid": "成品仓",
        "daopeijianleixing": ""
    },
    {
        "id": 65808,
        "peijianxuhao": 1,
        "daogongxu": "打脾",
        "shengchanzhouqi": 4,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "胶脾",
        "bengongxuid": "仓库脾开料",
        "bengongxu": "仓库脾开料",
        "daogongxuid": "打脾",
        "daopeijianleixing": ""
    
    },
    {
        "id": 13044,
        "peijianxuhao": 2,
        "daogongxu": "滚桶",
        "shengchanzhouqi": 7,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "胶脾",
        "bengongxuid": "打脾",
        "bengongxu": "打脾",
        "daogongxuid": "滚桶",
        "daopeijianleixing": ""
   
    },
    {
        "id": 125777,
        "peijianxuhao": 3,
        "daogongxu": "CNC",
        "shengchanzhouqi": 5,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "胶圈",
        "bengongxuid": "滚桶",
        "bengongxu": "滚桶",
        "daogongxuid": "CNC",
        "daopeijianleixing": ""
 
    },
    {
        "id": 46269,
        "peijianxuhao": 4,
        "daogongxu": "精雕",
        "shengchanzhouqi": 10,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "胶圈",
        "bengongxuid": "CNC",
        "bengongxu": "CNC",
        "daogongxuid": "精雕",
        "daopeijianleixing": ""
    
    },
    {
        "id": 6226,
        "peijianxuhao": 5,
        "daogongxu": "胶打磨",
        "shengchanzhouqi": 1,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "胶圈",
        "bengongxuid": "精雕",
        "bengongxu": "精雕",
        "daogongxuid": "胶打磨",
        "daopeijianleixing": ""

    },
    {
        "id": 88410,
        "peijianxuhao": 6,
        "daogongxu": "包装装配",
        "shengchanzhouqi": 3,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "胶圈",
        "bengongxuid": "胶打磨",
        "bengongxu": "胶打磨",
        "daogongxuid": "包装装配",
        "daopeijianleixing": "金属色架"
 
    },
    {
        "id": 35602,
        "peijianxuhao": 1,
        "daogongxu": "CNC前工序",
        "shengchanzhouqi": 5,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "胶圈",
        "bengongxuid": "仓库圈开料",
        "bengongxu": "仓库圈开料",
        "daogongxuid": "CNC前工序",
        "daopeijianleixing": ""
      
    },
    {
        "id": 110007,
        "peijianxuhao": 2,
        "daogongxu": "滚桶",
        "shengchanzhouqi": 0,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "胶圈",
        "bengongxuid": "CNC前工序",
        "bengongxu": "CNC前工序",
        "daogongxuid": "滚桶",
        "daopeijianleixing": ""
       
    },
    {
        "id": 125777,
        "peijianxuhao": 3,
        "daogongxu": "CNC",
        "shengchanzhouqi": 5,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "胶圈",
        "bengongxuid": "滚桶",
        "bengongxu": "滚桶",
        "daogongxuid": "CNC",
        "daopeijianleixing": ""
        
    },
    {
        "id": 46269,
        "peijianxuhao": 4,
        "daogongxu": "精雕",
        "shengchanzhouqi": 10,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "胶圈",
        "bengongxuid": "CNC",
        "bengongxu": "CNC",
        "daogongxuid": "精雕",
        "daopeijianleixing": ""
        
    },
    {
        "id": 6226,
        "peijianxuhao": 5,
        "daogongxu": "胶打磨",
        "shengchanzhouqi": 1,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "胶圈",
        "bengongxuid": "精雕",
        "bengongxu": "精雕",
        "daogongxuid": "胶打磨",
        "daopeijianleixing": ""
       
    },
    {
        "id": 88410,
        "peijianxuhao": 6,
        "daogongxu": "包装装配",
        "shengchanzhouqi": 3,
        "gongyinandu": null,
        "laiyuan": "自制",
        "peijianleixing": "胶圈",
        "bengongxuid": "胶打磨",
        "bengongxu": "胶打磨",
        "daogongxuid": "包装装配",
        "daopeijianleixing": "金属色架"
       
    }
],
    };
  },
  created() {
    let treeData = this.hadnlerTreeData(this.rowData);
    
    this.hierarchy = treeData;
    this.toggleExpand(this.hierarchy, true);
  },
  methods: {
    hadnlerTreeData(rowdata){
        let treeData = this.generateTree(rowdata);
        let allData = []
        for(let i = 0; i < treeData.length; i++){
          let obj = {
              id: treeData[i].id,
              peijianxuhao: (Number(treeData[i].peijianxuhao) + 1),
              daogongxu: '',
              shengchanzhouqi: treeData[i].shengchanzhouqi,
              gongyinandu: treeData[i].gongyinandu,
              laiyuan: treeData[i].laiyuan,
              peijianleixing: treeData[i].peijianleixing,
              bengongxuid: treeData[i].daogongxuid,
              bengongxu: treeData[i].daogongxuid,
              daogongxuid: '',
              daopeijianleixing: '',
              children:[]
          }
          obj.children.push(treeData[i])
          allData.push(obj)
        }
        return allData;
    },
    buildTree(data) {
      // 创建节点映射表
      const nodeMap = new Map();
      // 记录所有bengongxuid用于根节点判断
      const allBengongxuids = new Set();

      // 初始化节点
      data.forEach(item => {
        nodeMap.set(item.daogongxuid, {
          id: item.id,
          name: item.daogongxu,
          type: item.peijianleixing,
          cycle: item.shengchanzhouqi,
          children: [],
          bengongxuid: item.bengongxuid,
          daogongxuid: item.daogongxuid
        });
        allBengongxuids.add(item.bengongxuid);
      });

      // 构建反向父子关系
      data.forEach(item => {
        const parent = nodeMap.get(item.daogongxuid);
        const child = nodeMap.get(item.bengongxuid);

        if (parent && child) {
          // 去重检查
          const existing = parent.children.find(c => 
            c.bengongxuid === child.bengongxuid && 
            c.daogongxuid === child.daogongxuid
          );

          if (!existing) {
            // 类型判断
            const sameTypeChild = parent.children.find(c => 
              c.type === child.type
            );

            if (sameTypeChild) {
              // 合并相同类型子节点
              sameTypeChild.children = this.mergeChildren(
                sameTypeChild.children,
                child.children
              );
            } else {
              // 添加为同级节点
              parent.children.push(child);
            }
          }
        }
      });

      // 获取根节点
      return Array.from(nodeMap.values()).filter(node => 
        !allBengongxuids.has(node.daogongxuid)
      ).map(this.cleanNode);
    },

    generateTree(data) {
        // 去重，根据id唯一
        const uniqueData = data.filter(
          (v, i, a) => a.findIndex((t) => t.id === v.id) === i
        );

        // 收集所有bengongxuid
        const allBengongxuid = new Set(uniqueData.map((d) => d.bengongxuid));

        // 构建daogongxuid到节点的映射
        const nodesByDaogongxuid = uniqueData.reduce((acc, node) => {
          const key = node.daogongxuid;
          if (!acc[key]) {
            acc[key] = [];
          }
          acc[key].push(node);
          return acc;
        }, {});

        // 递归构建树
        function buildTree(bengongxu) {
          const children = nodesByDaogongxuid[bengongxu] || [];
          // 按bengongxuid和peijianleixing分组
          const groups = children.reduce((acc, child) => {
            const key = `${child.bengongxuid}|${child.peijianleixing}`;
            if (!acc[key]) {
              acc[key] = [];
            }
            acc[key].push(child);
            return acc;
          }, {});

          return Object.entries(groups).map(([key, group]) => {
            const firstChild = group[0]; // 取第一个代表节点
            return {
              ...firstChild,
              children: buildTree(firstChild.bengongxuid),
            };
          });
        }

        // 找到根节点（daogongxuid不在任何bengongxuid中的节点）
        const rootNodes = uniqueData.filter(
          (node) => !allBengongxuid.has(node.daogongxuid)
        );

        // 构建完整树结构
        return rootNodes.map((root) => ({
          ...root,
          children: buildTree(root.bengongxuid),
        }));
    },

    // 清理不需要的字段
    cleanNode(node) {
      return {
        id: node.id,
        name: node.name,
        type: node.type,
        cycle: node.cycle,
        children: node.children.map(this.cleanNode)
      }
    },

    // 合并子节点并去重
    mergeChildren(existing, newcomers) {
      const merged = [...existing];
      const keys = new Set(existing.map(n => `${n.daogongxuid}-${n.bengongxuid}`));
      
      newcomers.forEach(n => {
        const key = `${n.daogongxuid}-${n.bengongxuid}`;
        if (!keys.has(key)) {
          merged.push(n);
          keys.add(key);
        }
      });
      
      return merged;
    },
    NodeClick(e, data) {
          console.log("edata:", e, data)
            // 当前项的所有详情 如：id label children
        },
        collapse(list) {
            var _this = this;
            list.forEach(function (child) {
            if (child.expand) {
                child.expand = false;
            }
            child.children && _this.collapse(child.children);
            });
        },
        onExpand(e, data) {
            if ("expand" in data) {
            data.expand = !data.expand;
            if (!data.expand && data.children) {
                this.collapse(data.children);
            }
            } else {
              this.$set(data, "expand", true);
            }
        },
        toggleExpand(data, val) {
            var _this = this;
            if (Array.isArray(data)) {
            data.forEach(function (item) {
                _this.$set(item, "expand", val);
                if (item.children) {
                _this.toggleExpand(item.children, val);
                }
            });
            } else {
            this.$set(data, "expand", val);
            if (data.children) {
                _this.toggleExpand(data.children, val);
            }
            }
        },
    // 添加工序方法
    handlerAddRow(){
          this.$emit('hadnlerFlowMenu',0, [])
        },
        // 添加，编辑，删除
        handleAddDel(arg, rowdata){
            console.log("arg:", arg, rowdata)
            if(arg == 'addTreeSel'){ //添加新工序
                this.$emit('hadnlerFlowMenu',1, rowdata)
            }else if(arg == 'updateTreeSel'){ //编辑工序
                this.$emit('hadnlerFlowMenu',2, rowdata)
            }else if(arg == 'delTreeSel'){ //删除部门
                this.$confirm(this.$t('messagetext.tipsdelete'), this.$t('button.Tips'), {
                    confirmButtonText:this.$t('button.submit'),
                    cancelButtonText: this.$t('button.cancel'),
                    type: 'warning'
                }).then(() => {
                    this.$emit('hadnlerFlowMenu', 3, rowData.id)
                }).catch(() => {

                })
            }else if(arg == 'addProcess'){//添加工序
                this.$emit('addProcess',this.nodeData);
            }	
		},

    renderContent(h, rdata) {
            let day1 = this.$t('button.day');
            let languages = this.$t('language');
            return (<el-dropdown trigger='click' oncommand={(command) => this.handleAddDel(command, rdata)}>
                <a><div style="display:flex;flex-direction: column;justify-content: center;color:#fff;height:30px;line-height:30px;padding:15px 0;">
                    <div>{rdata.bengongxuid}<strong>{rdata.peijianleixing?'—'+rdata.peijianleixing:''}</strong></div>
                    {/* <div style="font-size:12px;margin-top:4px;">({data.end_day - data.start_day + 1 +" "+ day1})</div>
                    {data.start == 1 || data.end == 1 ? data.start == 1 && data.end == 0?<div style="color:#42b983;">{data.start_day}-{data.end_day}</div>:<div style="color:#FF0000;">{data.start_day}-{data.end_day}</div>:<div>{data.start_day}-{data.end_day}</div>} */}
                </div></a>
                <el-dropdown-menu slot='dropdown'>
                    <el-dropdown-item command='addTreeSel'>添加新工序</el-dropdown-item>
                    <el-dropdown-item command='updateTreeSel'>编辑工序</el-dropdown-item>
                    <el-dropdown-item command='delTreeSel' >删除工序</el-dropdown-item >
                    <el-dropdown-item command='addProcess' >工序管理</el-dropdown-item >

                </el-dropdown-menu >
            </el-dropdown >)
		},
  }
};
</script>

<style lang='scss' scope>
  .org-tree-container {
    display: inline-block;
    padding: 15px;
    background-color: #fff;
  }
  .org-tree {
    display: table;
    text-align: center;
  }
  .org-tree:after,
  .org-tree:before {
    content: "";
    display: table;
  }
  .org-tree:after {
    clear: both;
  }
  .org-tree-node,
  .org-tree-node-children {
    position: relative;
    margin: 0;
    padding: 0;
    list-style-type: none;
  }
  .org-tree-node-children:after,
  .org-tree-node-children:before,
  .org-tree-node:after,
  .org-tree-node:before {
    transition: all 0.35s;
  }
  .org-tree-node-label {
    position: relative;
    display: inline-block;
  }
  .org-tree-node-label .org-tree-node-label-inner {
    padding: 15px 18px;
    text-align: center;
    border-radius: 4px;
    box-shadow: 0 1px 5px rgba(0, 0, 0, 0.15);
  }
  .org-tree-node-btn {
    position: absolute;
    top: 100%;
    left: 50%;
    width: 20px;
    height: 20px;
    z-index: 10;
    margin-left: -11px;
    margin-top: 9px;
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 50%;
    box-shadow: 0 0 2px rgba(0, 0, 0, 0.15);
    cursor: pointer;
    transition: all 0.35s ease;
    display: none;
  }
  .org-tree-node-btn:hover {
    background-color: #e7e8e9;
    -webkit-transform: scale(1.15);
    transform: scale(1.15);
  }
  .org-tree-node-btn:after,
  .org-tree-node-btn:before {
    content: "";
    position: absolute;
  }
  .org-tree-node-btn:before {
    top: 50%;
    left: 4px;
    right: 4px;
    height: 0;
    border-top: 1px solid #ccc;
  }
  .org-tree-node-btn:after {
    top: 4px;
    left: 50%;
    bottom: 4px;
    width: 0;
    border-left: 1px solid #ccc;
  }
  .org-tree-node-btn.expanded:after {
    border: none;
  }
  .org-tree-node {
    padding-top: 20px;
    display: table-cell;
    vertical-align: top;
  }
  .org-tree-node.collapsed,
  .org-tree-node.is-leaf {
    padding-left: 10px;
    padding-right: 10px;
  }
  .org-tree-node:after,
  .org-tree-node:before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 50%;
    height: 19px;
  }
  .org-tree-node:after {
    left: 50%;
    border-left: 2px solid #333;
  }
  .org-tree-node:not(:first-child):before,
  .org-tree-node:not(:last-child):after {
    border-top: 2px solid #333;
  }
  .collapsable .org-tree-node.collapsed {
    padding-bottom: 30px;
  }
  .collapsable .org-tree-node.collapsed .org-tree-node-label:after {
    content: "";
    position: absolute;
    top: 100%;
    left: 0;
    width: 50%;
    height: 30px;
    border-right: 2px solid #333;
  }
  .org-tree > .org-tree-node {
    padding-top: 0;
  }
  .org-tree > .org-tree-node:after {
    border-left: 0;
  }
  .org-tree-node-children {
    padding-top: 30px;
    display: table;
  }
  .org-tree-node-children:before {
    content: "";
    position: absolute;
    top: 0;
    left: 50%;
    width: 0;
    height: 30px;
    border-left: 2px solid #333;
  }
  .org-tree-node-children:after {
    content: "";
    display: table;
    clear: both;
  }
  .horizontal .org-tree-node {
    display: table-cell;
    float: none;
    padding-top: 0;
    padding-left: 20px;
  }
  .horizontal .org-tree-node.collapsed,
  .horizontal .org-tree-node.is-leaf {
    padding-top: 10px;
    padding-bottom: 10px;
  }
  .horizontal .org-tree-node:after,
  .horizontal .org-tree-node:before {
    width: 19px;
    height: 50%;
  }
  .horizontal .org-tree-node:after {
    top: 50%;
    left: 0;
    border-left: 0;
  }
  .horizontal .org-tree-node:only-child:before {
    top: 1px;
    border-bottom: 2px solid #333;
  }
  .horizontal .org-tree-node:not(:first-child):before,
  .horizontal .org-tree-node:not(:last-child):after {
    border-top: 0;
    border-left: 2px solid #333;
  }
  .horizontal .org-tree-node:not(:only-child):after {
    border-top: 2px solid #333;
  }
  .horizontal .org-tree-node .org-tree-node-inner {
    display: table;
  }
  .horizontal .org-tree-node-label {
    display: table-cell;
    vertical-align: middle;
  }
  .horizontal.collapsable .org-tree-node.collapsed {
    padding-right: 30px;
  }
  .horizontal.collapsable .org-tree-node.collapsed .org-tree-node-label:after {
    top: 0;
    left: 100%;
    width: 30px;
    height: 50%;
    border-right: 0;
    border-bottom: 2px solid #333;
  }
  .horizontal .org-tree-node-btn {
    top: 50%;
    left: 100%;
    margin-top: -11px;
    margin-left: 9px;
  }
  .horizontal > .org-tree-node:only-child:before {
    border-bottom: 0;
  }
  .horizontal .org-tree-node-children {
    display: table-cell;
    padding-top: 0;
    padding-left: 20px;
  }
  .horizontal .org-tree-node-children:before {
    top: 49%;
    left: 0;
    width: 30px;
    height: 0;
    border-left: 0;
    border-top: 2px solid #333;
  }
  .horizontal .org-tree-node-children:after {
    display: none;
  }
  .horizontal .org-tree-node-children > .org-tree-node {
    display: block;
  }
  .bg-color-orange {
    color: #fff;
    background-color: #b22222;
  }
  /* 盒子css */
  .floating {
    background: rgba(255,255,255,.9);
    width: 200px;
    min-height: 300px;
    position: absolute;
    color: #333;
    padding: 15px;
    border-radius: 4px;
    padding-left: 4px; 
    box-sizing: border-box;
    left: 0;
    top: 0;
    transition: all 0.3s;
    z-index: 999;
    text-align: left;
    font-size: 13px;
    line-height:18px;
    box-shadow: 1px 7px 6px 5px rgba(0,0,0,.1);
  }
  a{color:#fff;}
  </style>
